//
//  MMGVideoPrizeClawViewModel.m
//  MyApp
//
//  Created by Don on 2017/9/1.
//  Copyright © 2017年 com.memego. All rights reserved.
//

#import "MMGVideoPrizeClawViewModel.h"
#import "MMGSocketClient.h"
#import "MMGSocketClient+MessageSender.h"


@interface MMGVideoPrizeClawViewModel ()

@end

@implementation MMGVideoPrizeClawViewModel {
    dispatch_source_t _ctimer;
}

- (instancetype)init {
    if (self = [super init]) {
        //TODO: - register socket msg notification
        [self socketMsgNotificationRegister];
    }
    return self;
}

#pragma mark - public
- (void)starSocket {
    
    [[MMGSocketClient shareMMGSocketClient] connectServerHost:kSERVICE_HOST port:2005];
}
- (void)closeSocket {
    [[MMGSocketClient shareMMGSocketClient] closeSocket];
}

- (void)sendConnectPrizeClawMachineMsg:(NSString *)machinId {
    [[MMGSocketClient shareMMGSocketClient] sendConnectPrizeClawMachineMsg:machinId];
}

- (void)sendUserAuthoMsg:(NSString *)authoCode {
    [[MMGSocketClient shareMMGSocketClient] sendUserAuthoMsg:authoCode];
}
- (void)sendGameReserveMsg {
    [[MMGSocketClient shareMMGSocketClient] sendGameReserveMsg];
}
- (void)sendGameStartMsg:(NSString *)limitTime {
    [[MMGSocketClient shareMMGSocketClient] sendGameStartMsg:limitTime];
}

- (void)sendPrizeClawMachineControlMsgWith:(float)radian {
    NSString *direction = kMMG_SOCKET_MSG_CONTROL_DOWN;
    
    if (fabs(radian) < 0.39) {
        direction = kMMG_SOCKET_MSG_CONTROL_RIGHT;
    }else if (fabs(radian) > 2.74) {
        direction = kMMG_SOCKET_MSG_CONTROL_LEFT;
    }else if (fabs(radian) > 1.17 && fabs(radian) < 1.96) {
        
        if (radian < 0) {
            direction = kMMG_SOCKET_MSG_CONTROL_UP;
        }else {
            direction = kMMG_SOCKET_MSG_CONTROL_DOWN;
        }
    
    }else if (fabs(radian) >= 1.96  && fabs(radian) <= 2.74) {
        if (radian < 0) {
            direction = kMMG_SOCKET_MSG_CONTROL_UP_LEFT;
        }else {
            direction = kMMG_SOCKET_MSG_CONTROL_DOWN_LEFT;
        }
    }else if (fabs(radian) >= 0.39 && fabs(radian) <= 1.17) {
        if (radian < 0) {
            direction = kMMG_SOCKET_MSG_CONTROL_UP_RIGHT;
        }else {
            direction = kMMG_SOCKET_MSG_CONTROL_DOWN_RIGHT;
        }
    }
    
    DLog(@"direction : %@",direction);
    [[MMGSocketClient shareMMGSocketClient] sendPrizeClawMachineControlMsgWith:direction];
}

- (void)sendStartClawMsg {
    [[MMGSocketClient shareMMGSocketClient] sendStartClawMsg];
}

- (void)sendWinPrizeMsg {
    [[MMGSocketClient shareMMGSocketClient] sendWinPrizeMsg];
}


- (void)startCountDownWithTimeSec:(int)sec counting:(void (^)(int))countingCallback overCount:(void (^)(int))timeOutCallback {
    DLog(@"startCountDownWithTimeSec ");
    if (_ctimer) {
        return;
    }
    __block int timeout=sec; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _ctimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_ctimer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_ctimer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_ctimer);
            _ctimer = nil;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                if (timeOutCallback) {
                    timeOutCallback(0);
                }
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                if (countingCallback) {
                    countingCallback(timeout);
                }
            });
            timeout--;
            
        }
    });
    dispatch_resume(_ctimer);
}


#pragma mark - private
- (void)socketMsgNotificationRegister {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSocketDidOpen) name:kMMG_Notification_SocketDidOpen object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSocketDidFailWithError:) name:kMMG_Notification_SocketDidFailWithError object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSocketDidClose) name:kMMG_Notification_SocketDidClose object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSocketHeartbeatTimeout) name:kMMG_Notification_SocketHeartOutTime object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSocketDidRececiveMessage:) name:kMMG_Notification_SocketDidReceiveMsg object:nil];
}

- (void)onSocketDidOpen {
}
- (void)onSocketDidFailWithError:(NSNotification *)notify {
}
- (void)onSocketDidClose {
    DLog(@"socket did close ");
}
- (void)onSocketHeartbeatTimeout {
}

- (void)onSocketDidRececiveMessage:(NSNotification *)notify {
    MMGSocketMsgModel *sockekMsg = (MMGSocketMsgModel *)notify.object;
    if ([sockekMsg isKindOfClass:[MMGSocketMsgModel class]]) {
        
//        if (sockekMsg.code == 0)
        {
            DLog(@"------------------------------- currentMsgType %d -------",sockekMsg.type);
            switch (sockekMsg.type) {
                case EMMMGSocketMsgAckTypeSyncTime: {
                    [self handleSyncTimeAckMsg:sockekMsg];
                }
                    break;
                case EMMMGSocketMsgAckTypeLogin: {
                    DLog(@"user did login ...");
                    //用户登入授权完成，开始连接设备
                    [self handleLoginAckMsg:sockekMsg];
                    
                }
                    break;
                case EMMMGSocketMsgAckTypeConnectedDevice: {
                    DLog(@"device did connect ...");
                    //激活按钮，需要预约游戏
                    [self handleConnectedDeviceAckMsg:sockekMsg];
                }
                    break;
                case EMMMGSocketMsgAckTypeReserveGame: {
                    DLog(@"预约成功并准备游戏 ....");
                    //预约成功，预约成功后服务器会返回游戏准备，如果不成功需要重新预约（激活预约按钮）
                    [self handleReserveGameAckMsg:sockekMsg];
                }
                    break;
                case EMMMGSocketMsgAckTypeReadyStartGame: {
                    //游戏准备完成 ，激活开始游戏按钮
                    DLog(@"游戏准备完成 ....");
                    [self handleReadyGameAckMsg:sockekMsg];
                    
                }
                    break;
                case EMMMGSocketMsgAckTypeStartGame: {
                    //成功开始游戏，激活摇杆和下爪按钮
                    DLog(@"开始游戏 ....");
                    [self handleStartGameAckMsg:sockekMsg];
                }
                    break;
                case EMMMGSocketMsgAckTypeControlDevice: {
                    [self handleControlDeviceAckMsg:sockekMsg];
                }
                    break;
                    
                case EMMMGSocketMsgAckTypeDownClaw: {
                    DLog(@"下爪指令发送成功 ...");
                    [self handleDownClawAckMsg:sockekMsg];
                }
                    break;
                case EMMMGSocketMsgAckTypeWinPraize: {
                    DLog(@"成功抓取娃娃 ...");
                    [self handleWinPraizeAckMsg:sockekMsg];
                    
                }
                    break;
                case EMMMGSocketMsgAckTypeHeartbeat: {
                    DLog(@"这是心跳 .....");
                }
                    break;
                    
                default:
                    break;
            }
        }
//        else {
//            DLog(@"error with msg :%@",sockekMsg.data);
//        }
       
        
    }
    

}

#pragma socket msg handler
- (void)handleSyncTimeAckMsg:(MMGSocketMsgModel *)msgModel {
    if (msgModel.code == 0) {
        [self sendUserAuthoMsg:kDEVICE_USER_AUTHO_CODE];
    }else {
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
    }
}

- (void)handleLoginAckMsg:(MMGSocketMsgModel *)msgModel {
    if (msgModel.code == 0) {
        [self sendConnectPrizeClawMachineMsg:kPRIZE_CLAW_MACHINE_ID];
    }else {
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
    }
}

- (void)handleConnectedDeviceAckMsg:(MMGSocketMsgModel *)msgModel {
    if (msgModel.code == 0) {
        //连接、重连
        if (self.vpcvState != EMMMGVideoPrizeClawViewStateJoystick) {
            //连接时激活预约按钮、重连不需要设置
            self.vpcvState = EMMMGVideoPrizeClawViewStateOrderGame;
        }
        
    }else {
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
    }

}


/**
 处理激活命令返回信息
 
 预约成功，预约成功后服务器会返回游戏准备，如果不成功需要重新预约（激活预约按钮）
 
 @param msgModel 激活命令返回信息
 */
- (void)handleReserveGameAckMsg:(MMGSocketMsgModel *)msgModel {
    if (msgModel.code == 0) {
        
    }else {
        self.vpcvState = EMMMGVideoPrizeClawViewStateOrderGame;
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
    }
}

- (void)handleReadyGameAckMsg:(MMGSocketMsgModel *)msgModel {
    if (msgModel.code == 0) {
        //游戏准备完成，激活开始游戏按钮
        self.vpcvState = EMMMGVideoPrizeClawViewStateStartGame;
    }else {
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
        self.vpcvState = EMMMGVideoPrizeClawViewStateOrderGame;
        [SVProgressHUD showErrorWithStatus:msgModel.data];
    }
    
}
- (void)handleStartGameAckMsg:(MMGSocketMsgModel *)msgModel {
    if (msgModel.code == 0) {
        //成功开始游戏，激活摇杆和下爪按钮
        self.vpcvState = EMMMGVideoPrizeClawViewStateJoystick;
    }else {
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
    }

}
- (void)handleControlDeviceAckMsg:(MMGSocketMsgModel *)msgModel {
    if (msgModel.code == 0) {
    }else {
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
    }
}
- (void)handleDownClawAckMsg:(MMGSocketMsgModel *)msgModel {
    if (msgModel.code == 0) {
    }else {
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
    }
}

- (void)handleWinPraizeAckMsg:(MMGSocketMsgModel *)msgModel {
    DLog(@"code:%d  msg :%@",msgModel.code,msgModel.data);
    [self sendWinPrizeMsg];
    self.vpcvState = EMMMGVideoPrizeClawViewStateOrderGame;
    
    if (msgModel.code == 0) {
        [SVProgressHUD showSuccessWithStatus:msgModel.data];
    }else {
        [SVProgressHUD showErrorWithStatus:msgModel.data];
        DLog(@"error code:%d  msg :%@",msgModel.code,msgModel.data);
    }
}


@end
